<template>
  <div>
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      labelAlign="left"
    >
      <a-form-item
        label="姓  名"
        name="name"
        style="width: 580px"
        labelAlign="right"
      >
        <a-input v-model:value="formState.name" style="border-radius: 5px" />
      </a-form-item>
      <a-form-item
        label="身份证号"
        :name="['sub', 'name']"
        style="width: 580px; border-radius: 15px"
        labelAlign="right"
      >
        <a-input
          v-model:value="formState.sub.name"
          style="border-radius: 5px"
        />
      </a-form-item>
      <a-select v-model:value="secondCity" style="width: 120px">
        <a-select-option v-for="city in cities" :key="city">
          {{ city }}
        </a-select-option>
      </a-select>
    </a-form>
  </div>
</template>

<script>
const provinceData = ["Zhejiang", "Jiangsu"];
const cityData = {
  Zhejiang: ["Hangzhou", "Ningbo", "Wenzhou"],
  Jiangsu: ["Nanjing", "Suzhou", "Zhenjiang"],
};
import { defineComponent, reactive, toRefs, computed, watch, ref,toRaw } from "vue";

export default defineComponent({   
  setup() {
    const formRef = ref();
    const formState = reactive({
      name: undefined,
      sub: {
        name: undefined,
      },
    });
    const rules = {
      name: [
        {
          required: true,
          message: "请输入姓名，要求必须是中文并且名字长度2-4位",
          pattern: /^[\u4e00-\u9fa5]{2,4}$/,
          min: 2,
          max: 4,
        },
      ],
      sub: {
        name: [
          {
            required: true,
            message: "请输入身份证号",
          },
          {
            min: 18,
            max: 18,
            message: "身份证号码必须是18位数",
            pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
            trigger: "blur",
          },
        ],
      },
    };

    const onSubmit = () => {
      formRef.value
        .validate()
        .then(() => {
          console.log("values", formState, toRaw(formState));
        })
        .catch((error) => {
          console.log("error", error);
        });
    };


    const province = provinceData[0];
    const state = reactive({
      province,
      provinceData,
      cityData,
      secondCity: cityData[province][0],
    });
    const cities = computed(() => {
      return cityData[state.province];
    });
    watch(
      () => state.province,
      (val) => {
        state.secondCity = state.cityData[val][0];
      }
    );


    return {
      formRef,
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 14,
      },
      formState,
      rules,
      onSubmit,
      ...toRefs(state), cities
    };
  },
});
</script>

<style>
</style>